package com.doge.walknovel.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.math.max

object BitmapUtils {
    fun readPictureDegree(path: String?): Int {
        if (path == null) return 0
        var degree = 0
        try {
            val exifInterface = ExifInterface(path)
            val orientation = exifInterface.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL
            )
            when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> degree = 90
                ExifInterface.ORIENTATION_ROTATE_180 -> degree = 180
                ExifInterface.ORIENTATION_ROTATE_270 -> degree = 270
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        return degree
    }

    /** 计算所需图片的缩放比例 */
    private fun calculateSampleSize(height: Int, width: Int, options: BitmapFactory.Options): Int {
        val realHeight = options.outHeight
        val realWidth = options.outWidth
        val heightScale = realHeight / height
        val widthScale = realWidth / width
        return max(widthScale, heightScale)
    }

    /** 根据文件路径获取指定大小的Bitmap对象*/
    fun getBitmapFromFile(path: String?, height: Int, width: Int): Bitmap? {
        if (path.isNullOrEmpty()) return null
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true // 只读取图片，不加载到内存中
        BitmapFactory.decodeFile(path, options)
        options.inSampleSize = calculateSampleSize(height, width, options)
        options.inJustDecodeBounds = false // 加载到内存中
        return BitmapFactory.decodeFile(path, options)
    }

    /** 旋转图片*/
    fun rotateBitmap(angle: Int, bitmap: Bitmap?): Bitmap? {
        if (bitmap == null) return null
        // 旋转图片
        val matrix = Matrix()
        matrix.postRotate(angle.toFloat())
        // 创建新的图片
        return Bitmap.createBitmap(
            bitmap, 0, 0,
            bitmap.width, bitmap.height, matrix, true
        )
    }

    fun saveBitmap(bitmap: Bitmap?, f: File) {
        if (bitmap == null) return

        if (f.exists()) f.delete()
        var out: FileOutputStream? = null
        try {
            out = FileOutputStream(f)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
            out.flush()
            out.close()
        } catch (e: Throwable) {
            e.printStackTrace()
        } finally {
            closeQuietly(out)
        }
    }

}